<template>
  <div>
    <a-drawer
      height="90%"
      placement="bottom"
      v-model:visible="visible"
      title="状态监测"
      @close="loading = false"
      unmount-on-close
    >
      <template #footer>
        <div class="flex-center">
          <a-space>
            <a-button @click="visible = false">取消</a-button>
            <a-button type="primary" @click="getStatus(false)" :loading="loading">重新检测</a-button>
          </a-space>
        </div>
      </template>
      <div class="flex flex-j-c box">
        <div class="tr">
          <GiChart width="300px" height="300px" :option="chartOption"></GiChart>
        </div>
        <div class="flex-col ml-15n textff8d1a mt-5n">
          <span class="flex flex-a-c">
            <div v-if="loading" class="flex-col">
              <div class="flex flex-a-c">
                <span>检测中</span>
                <div class="content mb-4 mr-m">
                  <div class="point1"></div>
                  <div class="point2"></div>
                  <div class="point3"></div>
                </div>
              </div>
              <template v-if="problem > 0">
                <span class="textff8d1a text-size-20 mb-6">发现{{ problem }}项问题</span>
              </template>
            </div>
            <template v-else>
              <template v-if="problem > 0">
                <span class="textff8d1a text-size-20 mb-6 mt-20 texttheme">发现{{ problem }}项问题</span>
              </template>
              <template v-else>
                <span class="text-align-center">
                  <span class="iconfont icon-dianzan mr-m text-size-30"></span>
                  <span>一切健康，未发现问题！</span>
                </span>
              </template>
            </template>
          </span>
          <span class="text-size-16" v-if="time">最近检测时间：{{ time }}</span>
        </div>
      </div>
      <a-table :columns="columns" :data="data" :pagination="false" :row-key="key">
        <template #item="{ record }">
          <div class="box">
            <a-button :loading="record.loading" type="text" size="large" :status="record.status">
              <template #icon>
                <icon-check-circle-fill v-if="record.status === 'success'" />
                <icon-close-circle-fill v-else-if="record.status === 'danger'" />
                <icon-desktop v-else />
              </template>
              {{ record.label }}
            </a-button>
          </div>
        </template>
        <template #result="{ record }">
          <div class="flex flex-a-c">
            <template v-if="record.message">
              <span>{{ record.message }}</span>
            </template>
            <template v-else>
              <span>{{ record.loading ? '正在检测' : '等待检测' }}</span>
            </template>
            <div class="content mb-4" v-if="record.loading">
              <div class="point1"></div>
              <div class="point2"></div>
              <div class="point3"></div>
            </div>
          </div>
        </template>
        <template #action="{ record }">
          <template v-if="record.status == 'normal' || record.loading">
            <span>--</span>
          </template>
          <template v-else-if="record.key == 0">
            <a-button type="primary" shape="round" @click="detectionReminderRenewalF">提醒续费</a-button>
          </template>
          <template v-else-if="record.status == 'success'">
            <a-button type="primary" shape="round" status="success">监测正常</a-button>
          </template>
          <template v-else-if="record.status == 'danger'">
            <a-button type="primary" shape="round" status="danger" @click="abnormal(record.key)">查看异常</a-button>
          </template>
        </template>
      </a-table>
    </a-drawer>
    <error-modal ref="ErrorModalRef"></error-modal>
  </div>
</template>

<script setup>
import {
  detectionDeviceStatus,
  detectionReminderRenewal,
  detectionMaterialGroupStatus,
  detectionOneKeyGroupStatus,
  detectionOneKeyGroupFail,
  detectionOneKeyMomentStatus,
  detectionOneKeyMomentFailList,
  detectionMomentStatus,
  detectionMomentFailList,
  detectionGroupStatus,
  detectionGroupFailList
} from '@/apis'
import { columnyjfqun, columnyjfquan, columnznfq, columnzxfq } from './data.js'
import { Message } from '@arco-design/web-vue'
import { useChart } from '@/hooks'
import { deepClone } from '@/utils/common'
import ErrorModal from './ErrorModal.vue'
import dayjs from 'dayjs'

const visible = ref(false)
const userWechatId = ref()
const problem = ref(0)
const time = ref()
const ErrorModalRef = ref()
const chartOptionO = ref({
  series: [
    {
      type: 'gauge',
      startAngle: 180,
      endAngle: 0,
      center: ['50%', '70%'],
      radius: '90%',
      min: 0,
      max: 1,
      splitNumber: 8,
      axisLine: {
        lineStyle: {
          width: 6,
          color: [
            [0.25, '#FF6E76'],
            [0.5, '#FDDD60'],
            [0.75, '#58D9F9'],
            [1, '#7CFFB2']
          ]
        }
      },
      pointer: {
        icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
        length: '12%',
        width: 20,
        offsetCenter: [0, '-60%'],
        itemStyle: {
          color: 'auto'
        }
      },
      axisTick: {
        length: 12,
        lineStyle: {
          color: 'auto',
          width: 2
        }
      },
      splitLine: {
        length: 20,
        lineStyle: {
          color: 'auto',
          width: 5
        }
      },
      axisLabel: {
        color: '#464646',
        fontSize: 20,
        distance: -44,
        rotate: 'tangential',
        formatter: function (value) {
          if (value === 0.875) {
            return '优'
          } else if (value === 0.625) {
            return '良'
          } else if (value === 0.375) {
            return '中'
          } else if (value === 0.125) {
            return '差'
          }
          return ''
        }
      },
      title: {
        offsetCenter: [0, '-10%'],
        fontSize: 20
      },
      detail: {
        fontSize: 30,
        offsetCenter: [0, '-35%'],
        valueAnimation: true,
        formatter: function (value) {
          return Math.round(value * 100) + ''
        },
        color: 'inherit'
      },
      data: [
        {
          value: 1,
          name: '健康度'
        }
      ]
    }
  ]
})

const columns = [
  {
    title: '检测项',
    slotName: 'item',
    width: 200
  },
  {
    title: '检测结果',
    slotName: 'result',
    width: 200
  },
  {
    title: '检测时间',
    dataIndex: 'time',
    render: ({ record }) => {
      return record.time || '--'
    },
    width: 200
  },
  {
    title: '操作',
    slotName: 'action',
    align: 'center',
    width: 100
  }
]

const dataReset = [
  {
    label: '设备状态',
    status: 'normal',
    message: '',
    time: '',
    key: 0,
    loading: false
  },
  {
    label: '智选跟群',
    status: 'normal',
    message: '',
    time: '',
    key: 1,
    loading: false
  },
  {
    label: '一键发群',
    status: 'normal',
    message: '',
    time: '',
    key: 2,
    loading: false
  },
  {
    label: '一键发圈',
    status: 'normal',
    message: '',
    time: '',
    key: 3,
    loading: false
  },
  {
    label: '智能发圈',
    status: 'normal',
    message: '',
    time: '',
    key: 4,
    loading: false
  },
  {
    label: '智选发群',
    status: 'normal',
    message: '',
    time: '',
    key: 5,
    loading: false
  }
]

const data = ref(deepClone(dataReset))

const loading = computed(() => {
  return (
    data.value[0].loading ||
    data.value[1].loading ||
    data.value[2].loading ||
    data.value[3].loading ||
    data.value[4].loading ||
    data.value[5].loading
  )
})

watch(
  () => data.value,
  (e) => {
    let m = 0
    e.forEach((element) => {
      if (element.status === 'danger') {
        m++
      }
    })
    problem.value = m
    chartOptionO.value.series[0].data[0].value = ((e.length - m) / e.length).toFixed(2)
  },
  {
    deep: true,
    immediate: true
  }
)

//设备状态检测
const detectionDeviceStatusF = async () => {
  const res = await detectionDeviceStatus({ userWechatId: userWechatId.value })
  setTimeout(() => {
    data.value[0].status = res.data.isFail ? 'danger' : 'success'
    data.value[0].time = res.data.detectionTime
    data.value[0].message = res.data.detectionIssues
    data.value[0].loading = false
    data.value[1].loading = true
    detectionMaterialGroupStatusF()
  }, 2000)
}

// 续费检测
const detectionReminderRenewalF = async () => {
  const res = await detectionReminderRenewal({ userWechatId: userWechatId.value })
  Message.success(res.data.detectionIssues)
}

// 智选跟圈检测
const detectionMaterialGroupStatusF = async () => {
  const res = await detectionMaterialGroupStatus({ userWechatId: userWechatId.value })
  setTimeout(() => {
    data.value[1].status = res.data.isFail ? 'danger' : 'success'
    data.value[1].time = res.data.detectionTime
    data.value[1].message = res.data.detectionIssues
    data.value[1].loading = false
    data.value[2].loading = true
    detectionOneKeyGroupStatusF()
  }, 2000)
}

// 一键发群检测
const detectionOneKeyGroupStatusF = async () => {
  const res = await detectionOneKeyGroupStatus({ userWechatId: userWechatId.value })
  setTimeout(() => {
    data.value[2].status = res.data.isFail ? 'danger' : 'success'
    data.value[2].time = res.data.detectionTime
    data.value[2].message = res.data.detectionIssues
    data.value[2].loading = false
    data.value[3].loading = true
    detectionOneKeyMomentStatusF()
  }, 2000)
}

// 一键发圈检测
const detectionOneKeyMomentStatusF = async () => {
  const res = await detectionOneKeyMomentStatus({ userWechatId: userWechatId.value })
  setTimeout(() => {
    data.value[3].status = res.data.isFail ? 'danger' : 'success'
    data.value[3].time = res.data.detectionTime
    data.value[3].message = res.data.detectionIssues
    data.value[3].loading = false
    data.value[4].loading = true
    detectionMomentStatusF()
  }, 2000)
}

// 智能发圈检测
const detectionMomentStatusF = async () => {
  const res = await detectionMomentStatus({ userWechatId: userWechatId.value })
  setTimeout(() => {
    data.value[4].status = res.data.isFail ? 'danger' : 'success'
    data.value[4].time = res.data.detectionTime
    data.value[4].message = res.data.detectionIssues
    data.value[4].loading = false
    data.value[5].loading = true
    detectionGroupStatusF()
  }, 2000)
}

// 智选发群检测
const detectionGroupStatusF = async () => {
  const res = await detectionGroupStatus({ userWechatId: userWechatId.value })
  setTimeout(() => {
    data.value[5].status = res.data.isFail ? 'danger' : 'success'
    data.value[5].time = res.data.detectionTime
    data.value[5].message = res.data.detectionIssues
    data.value[5].loading = false
    time.value = dayjs().format('YYYY-MM-DD HH:mm:ss')
  }, 2000)
}

// 打开编辑框并回显表单值
const getStatus = (userWechatIdO) => {
  if (userWechatIdO) {
    userWechatId.value = userWechatIdO
    visible.value = true
  }
  resetF()
}

const resetF = () => {
  data.value = deepClone(dataReset)
  data.value[0].loading = true
  detectionDeviceStatusF()
}

// 异常查看
const abnormal = async (key) => {
  let api = null
  let cloumn = null
  switch (key) {
    case 1:
      // api =
      break
    case 2:
      api = detectionOneKeyGroupFail
      cloumn = columnyjfqun
      break
    case 3:
      api = detectionOneKeyMomentFailList
      cloumn = columnyjfquan
      break
    case 4:
      api = detectionMomentFailList
      cloumn = columnznfq
      break
    case 5:
      api = detectionGroupFailList
      cloumn = columnzxfq
      break
    default:
      console.log(key)
      break
  }
  const res = await api({ userWechatId: userWechatId.value })
  ErrorModalRef?.value?.getData(res, cloumn)
}

const { chartOption } = useChart(() => {
  return chartOptionO.value
})

// onUnmounted(() => {
//   console.log(332)
// })

defineExpose({ getStatus })
</script>
<style scoped lang="scss">
.textff8d1a {
  color: #ff8d1a;
}
.box {
  :deep(.arco-btn-status-normal) {
    color: #333;
  }
  :deep(.arco-btn-text) {
    font-size: 15px;
    font-weight: 500;
  }
}
.tr {
  zoom: 0.76;
  margin-top: -50px;
}
.content {
  margin-left: 12px;
  div {
    width: 6px;
    height: 6px;
    background-color: #333;
    border-radius: 50%;
    display: inline-block;
    animation: action 1.5s infinite ease-in-out;
    animation-fill-mode: both;
  }
  .point1 {
    animation-delay: -0.3s;
  }
  .point2 {
    animation-delay: -0.1s;
  }
}
@keyframes action {
  0%,
  80%,
  100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.text-theme {
  color: rgb(var(--primary-6));
}
</style>
